﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraGrid.Views.Grid;
using System.IO;
using System.Collections;

namespace Print_UI
{
    public partial class FrmPrintReportTemplate : CommonForm
    {
        #region Contructors
        public FrmPrintReportTemplate()
        {
            InitializeComponent();
        }
        #endregion

        #region Private Members
        DataTable _dt;
        //  int g = 0;
        //  int f = 0;
        dsReport _ds = new dsReport();
        public class PrintCommandHandler : DevExpress.XtraPrinting.ICommandHandler
        {
            private CommandParams _cmd;

            public PrintCommandHandler(CommandParams cmd)
            {
                _cmd = cmd;
            }

            public void HandleCommand(DevExpress.XtraPrinting.PrintingSystemCommand command, object[] args, DevExpress.XtraPrinting.IPrintControl control, ref bool handled)
            {
                try
                {
                    Print();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }

            public virtual bool CanHandleCommand(DevExpress.XtraPrinting.PrintingSystemCommand command, DevExpress.XtraPrinting.IPrintControl control)
            {
                return command == DevExpress.XtraPrinting.PrintingSystemCommand.Print;
            }

            void Print()
            {
                _cmd.IsPrint = true;
            }
        }
        #endregion

        #region Event
        //Load form
        private void FrmPrintReportTemplate_Load(object sender, EventArgs e)
        {
            try
            {
                _dt = new DataTable();
                _dt = _ds.Student.Clone();
                _dt.Columns.Add("TemplateID", typeof(int));
                _dt.Columns.Add("TotalSubject", typeof(int));
                _dt.Columns.Add("StatusPrint", typeof(bool));
                _dt.Columns.Add("IsChoose", typeof(bool));
                _dt.Columns.Add("ID", typeof(int));
                LoadYear();

            }
            catch (Exception ex)
            {
                CommonError(ex);
            }
        }
        private void btnRefresh_ItemClick_1(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            cboClass.EditValue = -1;
            cboSemester.EditValue = -1;
            CboTemplate.EditValue = -1;
            cboYear.EditValue = -1;
        }
        //button save 
        private void btnSave_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                int j = 0;
                int k = 0;
                for (int i = 0; i < _dt.Rows.Count; i++)
                {
                    DataRow dr = _dt.Rows[i];
                    int id = Convert.ToInt32(dr["ID"]);
                    int templateID = Convert.ToInt32(dr["TemplateID"]);
                    bool status = Convert.ToBoolean(dr["IsChoose"]);

                    if (status == true)
                    {
                        if (templateID != -1)
                        {
                            var obj = Model.PRI_StudentInSemester.FirstOrDefault(c => c.ID == id);
                            if (obj != null)
                            {
                                obj.TemplateID = templateID;
                                obj.StatusPrint = true;
                            }
                        }
                        else
                        {
                            j = j + 1;
                        }
                        k = k + 1;
                    }
                }
                if (k == 0)
                {
                    CommonMessage("Chưa chọn sinh viên");
                }
                else
                {
                    if (j == _dt.Rows.Count)
                    {
                        CommonMessage("Sinh viên chưa có mẫu thư không thể lưu");
                    }
                    else
                    {
                        if (j > 0)
                        {
                            if (CommonConfirm("Chỉ Ghi nhận các sinh viên có mẫu thư đã in thư?", "Xác Nhận"))
                            {
                                Model.SaveChanges();
                                CommonMessage("Lưu thành công");
                                LoadData();
                                chkCheckAll.Checked = false;
                            }
                        }
                        else
                        {
                            if (j == 0)
                            {
                                if (CommonConfirm("Ghi nhận các sinh viên đã in thư?", "Xác Nhận"))
                                {
                                    Model.SaveChanges();
                                    CommonMessage("Lưu thành công");
                                    LoadData();
                                    chkCheckAll.Checked = false;
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        //button print
        private void btnPrint_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                DataRow[] drs = _dt.Select("IsChoose=1");
                if (drs.Length > 0)
                {
                    dsReport ds = new dsReport();
                    dsReport ds1 = new dsReport();
                    List<int> lst = new List<int>();
                    for (int i = 0; i < drs.Length; i++)
                    {
                        DataRow dr = drs[i];
                        DataRow drInsert = ds.Student.NewRow();
                        for (int j = 0; j < ds.Student.Columns.Count; j++)
                            drInsert[ds.Student.Columns[j].ColumnName] = dr[ds.Student.Columns[j].ColumnName];
                        ds.Student.Rows.Add(drInsert);
                        int template = Convert.ToInt32(dr["TemplateID"]);
                        if (!lst.Contains(Convert.ToInt32(dr["TemplateID"])))
                            lst.Add(Convert.ToInt32(dr["TemplateID"]));
                    }
                    int templateID = -1;
                    if (lst.Count > 1)
                    {
                        frmStudent_Choose frm = new frmStudent_Choose();
                        frm.ListID = lst;
                        if (frm.ShowDialog() == DialogResult.OK)
                        {
                            templateID = frm.ChooseID;
                            DataRow[] drs1;
                            DataTable tb = new DataTable();
                            tb = drs.CopyToDataTable();
                            drs1 = tb.Select("TemplateID='" + templateID + "'");
                            if (drs1.Length > 0)
                            {
                                for (int i = 0; i < drs1.Length; i++)
                                {
                                    DataRow dr = drs1[i];
                                    DataRow drInsert = ds1.Student.NewRow();
                                    for (int j = 0; j < ds1.Student.Columns.Count; j++)
                                    {
                                        drInsert[ds1.Student.Columns[j].ColumnName] = dr[ds1.Student.Columns[j].ColumnName];
                                    }
                                    ds1.Student.Rows.Add(drInsert);
                                }
                            }
                            if (templateID != -1)
                            {
                                var obj = Model.PRI_Template.FirstOrDefault(c => c.ID == templateID);
                                if (obj != null)
                                {
                                    if (obj.Stream != null)
                                    {
                                        Template rp = new Template();
                                        System.IO.MemoryStream ms = new System.IO.MemoryStream(obj.Stream);
                                        rp.LoadLayout(ms);
                                        rp.DataSource = ds1;
                                        DevExpress.XtraReports.UI.ReportPrintTool printTool = new DevExpress.XtraReports.UI.ReportPrintTool(rp);
                                        CommandParams cmd = new CommandParams();
                                        cmd.IsPrint = false;
                                        printTool.PrintingSystem.AddCommandHandler(new PrintCommandHandler(cmd));
                                        printTool.ShowPreviewDialog();
                                        if (cmd.IsPrint)
                                        {
                                            for (int i = 0; i < drs.Length; i++)
                                            {
                                                DataRow dr = drs[i];
                                                dr["IsPrint"] = true;
                                            }
                                        }
                                    }
                                }
                            }
                            else
                            {
                                CommonMessage("Chưa Chọn Mẫu thư");
                            }
                        }

                    }
                    else
                    {
                        templateID = lst[0];
                        if (templateID != -1)
                        {
                            var obj = Model.PRI_Template.FirstOrDefault(c => c.ID == templateID);
                            if (obj != null)
                            {
                                if (obj.Stream != null)
                                {
                                    Template rp = new Template();
                                    System.IO.MemoryStream ms = new System.IO.MemoryStream(obj.Stream);
                                    rp.LoadLayout(ms);
                                    rp.DataSource = ds;
                                    DevExpress.XtraReports.UI.ReportPrintTool printTool = new DevExpress.XtraReports.UI.ReportPrintTool(rp);
                                    CommandParams cmd = new CommandParams();
                                    cmd.IsPrint = false;
                                    printTool.PrintingSystem.AddCommandHandler(new PrintCommandHandler(cmd));
                                    printTool.ShowPreviewDialog();
                                    if (cmd.IsPrint)
                                    {
                                        for (int i = 0; i < drs.Length; i++)
                                        {
                                            DataRow dr = drs[i];
                                            dr["IsPrint"] = true;
                                        }
                                    }
                                }
                            }
                        }
                        else
                        {
                            CommonMessage("Chưa Chọn Mẫu thư");
                        }
                    }

                }
                else
                {
                    CommonMessage("Chưa Chọn Sinh Viên");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        //check/uncheck all student
        private void checkEdit1_CheckedChanged(object sender, EventArgs e)
        {
            if (chkCheckAll.Checked)
            {
                for (int i = 0; i < _dt.Rows.Count; i++) { _dt.Rows[i]["IsChoose"] = true; }
            }
            else
            {
                for (int i = 0; i < _dt.Rows.Count; i++) { _dt.Rows[i]["IsChoose"] = false; }
            }
        }
        private void cboYear_EditValueChanged(object sender, EventArgs e)
        {
            LoadSemester();
            LoadClass();
            LoadTemplateOfStudent();
            LoadData();
            checkused();
        }
        private void cboSemester_EditValueChanged(object sender, EventArgs e)
        {
            LoadClass();
            LoadTemplateOfStudent();
            LoadData();
            checkused();
        }
        private void CboTemplate_EditValueChanged(object sender, EventArgs e)
        {
            LoadTemplateOfStudent();
            Checkloadtemplate();
        }
        private void cboClass_EditValueChanged(object sender, EventArgs e)
        {

            LoadTemplate();
            LoadTemplateOfStudent();
            LoadData();
        }

        #endregion

        #region Private Members
        //load combobox year
        private void LoadYear()
        {
            var Year = (from p in Model.CAT_Year
                        join k in Model.PRI_SemesterSetting on p.ID equals k.YearID
                        select new { p.ID, p.Name }).Distinct();
            Dictionary<int, string> dic = new Dictionary<int, string>();
            dic.Add(-1, "----Chọn Năm Học----");
            foreach (var item in Year)
            {
                dic.Add(item.ID, item.Name);
            }

            cboYear.Properties.ValueMember = "Key";
            cboYear.Properties.DisplayMember = "Value";
            cboYear.Properties.DataSource = dic;
            cboYear.EditValue = -1;
        }
        //load combobox semester
        private void LoadSemester()
        {
            int i = Convert.ToInt32(cboYear.EditValue);
            var Semester = (from p in Model.CAT_Semester
                            join k in Model.PRI_SemesterSetting on p.ID equals k.SemesterID
                            where i == k.YearID
                            select new { p.ID, p.SemesterName }).Distinct();
            Dictionary<int, string> dic = new Dictionary<int, string>();
            dic.Add(-1, "--- Chọn Học Kì ---");
            foreach (var item in Semester)
            {
                dic.Add(item.ID, item.SemesterName);
            }
            cboSemester.Properties.ValueMember = "Key";
            cboSemester.Properties.DisplayMember = "Value";
            cboSemester.Properties.DataSource = dic;
            cboSemester.EditValue = -1;
        }
        //load combobox class of department in this year
        private void LoadClass()
        {
            try
            {
                int iYear = Convert.ToInt32(cboYear.EditValue);
                int iSemester = Convert.ToInt32(cboSemester.EditValue);
                var GetClass = (from obj in Model.PRI_StudentInSubject.Where(c => c.DepartmentID == DepartmentID && c.YearID == iYear && c.SemesterID == iSemester)
                                select new { obj.CAT_Class.ID, obj.CAT_Class.Name }).Distinct();
                Dictionary<int, string> dic = new Dictionary<int, string>();
                dic.Add(-1, "-----Chọn Lớp-----");
                foreach (var item in GetClass)
                {
                    dic.Add(item.ID, item.Name);
                }
                cboClass.Properties.ValueMember = "Key";
                cboClass.Properties.DisplayMember = "Value";
                cboClass.Properties.DataSource = dic;
                cboClass.EditValue = -1;

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        // Load Templates of Department in this year
        private void LoadTemplate()
        {
            int year = Convert.ToInt32(cboYear.EditValue);
            int semester = Convert.ToInt32(cboSemester.EditValue);
            var query = from obj in Model.PRI_Template.Where(c => c.DepartmentID == DepartmentID && c.YearID == year && c.SemesterID == semester)
                        select obj;
            Dictionary<int, string> dic = new Dictionary<int, string>();
            dic.Add(-1, "-----Chọn mẫu thư-----");
            foreach (var item in query)
            {
                dic.Add(item.ID, item.TemplateName);
            }
            CboTemplate.Properties.ValueMember = "Key";
            CboTemplate.Properties.DisplayMember = "Value";
            CboTemplate.Properties.DataSource = dic;
            CboTemplate.EditValue = -1;

        }
        // Load Template for each student 
        private void LoadTemplateOfStudent()
        {
            try
            {
                int year = Convert.ToInt32(cboYear.EditValue);
                int semester = Convert.ToInt32(cboSemester.EditValue);
                var template = from obj in Model.PRI_Template
                               where obj.DepartmentID == DepartmentID && obj.YearID == year && obj.SemesterID == semester
                               select new { obj.ID, obj.TemplateName };
                repositoryItemLookUpEdit1.DataSource = template;
                repositoryItemLookUpEdit1.DisplayMember = "TemplateName";
                repositoryItemLookUpEdit1.ValueMember = "ID";

            }
            catch (Exception ex)
            { MessageBox.Show(ex.Message); }
        }
        public byte[] ImageToByte(Image my_image)
        {
            MemoryStream Mstream = new MemoryStream();
            my_image.Save(Mstream, System.Drawing.Imaging.ImageFormat.Jpeg);

            return Mstream.ToArray();
        }
        //load data of student follow template in Database
        private void LoadData()
        {
            try
            {
                _dt.Clear();
                chkCheckAll.Checked = false;
                int iYear = Convert.ToInt32(cboYear.EditValue);
                int iSemester = Convert.ToInt32(cboSemester.EditValue);
                int iClassID = Convert.ToInt32(cboClass.EditValue);
                int iTemplateID = Convert.ToInt32(CboTemplate.EditValue);

                if (iYear != -1 && iSemester != -1 && iClassID != -1)
                {
                    var query1 = from h in Model.PRI_StudentInSemester
                                 where h.YearID == iYear && h.SemesterID == iSemester && h.ClassID == iClassID && h.DepartmentID == DepartmentID
                                 select new
                                 {
                                     h.StudentID,
                                     h.PRI_Student.Lastname,
                                     h.PRI_Student.Firstname,
                                     h.CAT_Class.Name,
                                     h.ClassID,
                                     h.CAT_Semester.SemesterName,
                                     year = h.CAT_Year.Name,
                                     h.TemplateID,
                                     h.StatusPrint,
                                     department = h.CAT_Department.Name,
                                     h.SchoolFee,
                                     h.TotalMoneyDebt,
                                     h.ID,
                                     h.SemesterAverage,
                                     h.SponsorBy,
                                     h.Address,
                                     h.SchoolFeeDebt,
                                     h.ResitFeeDebt
                                 };
                    var query2 = (from g in Model.PRI_SubjectSetting
                                  where g.YearID == iYear && g.SemesterID == iSemester &&
                                  g.ClassID == iClassID && g.DepartmentID == DepartmentID
                                  select
                                  new
                                  {
                                      g.SubjectID,
                                      g.IsMain,
                                      g.TeacherID,
                                      Signature = (g.TeacherID == null) ? null : g.PRI_Teacher.Signature
                                  }).ToList();
                    foreach (var item1 in query1)
                    {
                        int i = 1;
                        int j = 1;
                        int totalsubject = 0;
                        var query = from c in Model.PRI_StudentInSubject
                                    where c.StudentID == item1.StudentID
                                    && c.YearID == iYear && c.SemesterID == iSemester &&
                                    c.ClassID == iClassID && c.DepartmentID == DepartmentID
                                    select new
                                    {
                                        c.SubjectID,
                                        c.PRI_Subjects.SubjectName,
                                        c.TotalScore,
                                        c.Remarks,
                                        c.PRI_Subjects.Code
                                        // c.AttendanceScore,
                                        //  c.MidtermScore,
                                        //  c.FinalExamScore1,
                                        //   c.FinalExcamScore2,
                                    };
                        var d = Model.CAT_Class.FirstOrDefault(c => c.ID == item1.ClassID);
                        DataRow dt = _dt.NewRow();
                        dt["Name"] = item1.Firstname + " " + item1.Lastname;
                        dt["Class"] = item1.Name;
                        dt["Year"] = item1.year;
                        dt["Semester"] = item1.SemesterName;
                        dt["Department"] = item1.department;
                        dt["ID"] = item1.ID;
                        if (item1.TemplateID == null)
                        {
                            dt["TemplateID"] = -1;
                        }
                        else
                        {
                            dt["TemplateID"] = item1.TemplateID;
                        }
                        dt["SemesterAverage"] = item1.SemesterAverage;
                        dt["Sponsor"] = item1.SponsorBy;
                        dt["Address"] = item1.Address;
                        dt["StatusPrint"] = item1.StatusPrint;
                        dt["IsChoose"] = false;
                        if (d.SectorID == null)
                        {
                            dt["Sector"] = "";
                        }
                        else
                        {
                            dt["Sector"] = d.CAT_Sector.Name;
                        }
                        dt["SchoolFee"] = item1.SchoolFee.ToString("###,###,##0");
                        dt["TotalMoneyDebt"] = item1.TotalMoneyDebt.ToString("###,###,##0");
                        dt["SchoolFeeDebt"] = item1.SchoolFeeDebt.ToString("###,###,##0");
                        dt["ResitFeeDebt"] = item1.ResitFeeDebt.ToString("###,###,##0");

                        int len = item1.SchoolFee.ToString().Length;

                        if (item1.SchoolFee.ToString() != "0.0000")
                        {
                            dt["ConvertNumtoString"] = "(" + Doisosangchu(item1.SchoolFee.ToString().Substring(0, len - 5)) + " đồng chẵn)";
                        }
                        else
                        {
                            dt["ConvertNumtoString"] = "";
                        }
                        foreach (var item2 in query)
                        {
                            var g = query2.FirstOrDefault(c => c.SubjectID == item2.SubjectID);
                            if (g != null && g.IsMain == true)
                            {
                                dt["MainSubject" + i] = item2.SubjectName;
                                // dt["AMainScore" + i] = item2.AttendanceScore;
                                // dt["MMainScore" + i] = item2.MidtermScore;
                                //  dt["F1MainScore" + i] = item2.FinalExamScore1;
                                //   dt["F2MainScore" + i] = item2.FinalExcamScore2;
                                dt["TMainScore" + i] = item2.TotalScore;
                                dt["RemarksM" + i] = item2.Remarks;
                                if (g.Signature != null)
                                    dt["SignatureM" + i] = g.Signature;
                                dt["SubjectCodeM" + i] = item2.Code;
                                i++;
                                totalsubject++;
                            }
                            else
                            {
                                dt["SubSubject" + j] = item2.SubjectName;
                                //  dt["ASubScore" + j] = item2.AttendanceScore;
                                //   dt["MSubScore" + j] = item2.MidtermScore;
                                //   dt["F1SubScore" + j] = item2.FinalExamScore1;
                                //    dt["F2SubScore" + j] = item2.FinalExcamScore2;
                                dt["TSubScore" + j] = item2.TotalScore;
                                dt["RemarksS" + i] = item2.Remarks;
                                if (g.Signature != null)
                                    dt["SignatureS" + i] = g.Signature;
                                dt["SubjectCodeS" + i] = item2.Code;
                                j++;
                                totalsubject++;
                            }
                        }
                        dt["TotalSubject"] = totalsubject;
                        _dt.Rows.Add(dt);
                        grdData.DataSource = _dt;
                    }
                }
            }
            catch (Exception ex)
            {
                CommonError(ex);
            }

        }
        //check year is used
        private void checkused()
        {
            int year = Convert.ToInt32(cboYear.EditValue);
            int semester = Convert.ToInt32(cboSemester.EditValue);
            bool check = Model.PRI_SemesterSetting.Where(c => c.YearID == year && c.SemesterID == semester && c.IsUsed == true).Count() > 0;
            if (check)
            {
                btnSave.Enabled = true;
                btnPrint.Enabled = true;
                btnCancel.Enabled = true;
            }
            else
            {
                btnSave.Enabled = false;
                btnPrint.Enabled = false;
                btnCancel.Enabled = false;
            }
        }
        private void Checkloadtemplate()
        {
            int count = 0;
            if (CboTemplate.EditValue != null)
            {
                int temp = Convert.ToInt32(CboTemplate.EditValue);
                if (temp != -1)
                {
                    for (int i = 0; i < _dt.Rows.Count; i++)
                    {
                        int temp1 = Convert.ToInt32(_dt.Rows[i]["TemplateID"]);
                        if (temp1 != -1)
                        {
                            count++;
                        }
                    }
                    if (count == 0)
                    {
                        for (int i = 0; i < _dt.Rows.Count; i++)
                        {
                            int temp1 = Convert.ToInt32(_dt.Rows[i]["TemplateID"]);
                            _dt.Rows[i]["TemplateID"] = temp;
                        }
                    }
                    else
                    {
                        if (CommonConfirm("Bạn có muốn áp dụng mẫu thư cho tất cả sinh viên hay không?", "Thay Đổi mẫu thư"))
                        {
                            for (int i = 0; i < _dt.Rows.Count; i++)
                            {
                                int temp1 = Convert.ToInt32(_dt.Rows[i]["TemplateID"]);
                                _dt.Rows[i]["TemplateID"] = temp;
                            }
                        }
                        else
                        {
                            for (int i = 0; i < _dt.Rows.Count; i++)
                            {
                                int temp1 = Convert.ToInt32(_dt.Rows[i]["TemplateID"]);
                                if (temp1 == -1)
                                    _dt.Rows[i]["TemplateID"] = temp;
                            }
                        }
                    }
                }
            }
            grdData.DataSource = _dt;

        }
        private void gridView1_RowStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowStyleEventArgs e)
        {
            try
            {
                GridView View = sender as GridView;
                if (e.RowHandle >= 0)
                {
                    int iTemplateID = Convert.ToInt32(CboTemplate.EditValue);
                    int iGridviewTemplate = Convert.ToInt32(View.GetRowCellValue(e.RowHandle, View.Columns["TemplateID"]));
                    if (iGridviewTemplate != iTemplateID)
                    {
                        e.Appearance.BackColor = Color.Salmon;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

        static Hashtable hs = new Hashtable();
        static Hashtable h = new Hashtable();
        public static string Doisosangchu(string chuoi)
        {

            h["0"] = " nghìn ";
            h["1"] = " triệu ";
            h["2"] = " tỉ ";
            h["3"] = " nghìn tỉ ";
            h["4"] = " triệu tỉ ";
            h["5"] = " tỉ tỉ ";

            hs["0"] = "lẻ";
            hs["1"] = "một";
            hs["2"] = "hai";
            hs["3"] = "ba";
            hs["4"] = "bốn";
            hs["5"] = "năm";
            hs["6"] = "sáu";
            hs["7"] = "bảy";
            hs["8"] = "tám";
            hs["9"] = "chín";
            hs["10"] = "mười";
            hs["11"] = "mười một";
            hs["12"] = "mười hai";
            hs["13"] = "mười ba";
            hs["14"] = "mười bốn";
            hs["15"] = "mười lăm";
            hs["16"] = "mười sáu";
            hs["17"] = "mười bảy";
            hs["18"] = "mười tám";
            hs["19"] = "mười chín";
            hs["20"] = "hai mươi";
            hs["30"] = "ba mươi";
            hs["40"] = "bốn mươi";
            hs["50"] = "năm mươi";
            hs["60"] = "sáu mươi";
            hs["70"] = "bảy mươi";
            hs["80"] = "tám mươi";
            hs["90"] = "chín mươi";
            string returnkqua = "";

            string chuoicd;

            chuoicd = ThemDauPhayVaoChuoi(chuoi);

            int countdauphay = 0;
            foreach (char item in chuoicd)
            {
                if (item == ',')
                {
                    countdauphay++;
                }
            }

            string[] chuoiktra = chuoicd.Split(',');

            for (int i = 0; i < chuoiktra.Length; i++)
            {
                countdauphay = countdauphay - 1;
                returnkqua += KTText(chuoiktra[i]);
                if (chuoiktra[i] != "000")
                {
                    returnkqua += h[countdauphay.ToString()];
                }

            }
            return returnkqua;

        }

        public static string ThemDauPhayVaoChuoi(string chuoi)
        {
            string chuoicd;
            int sodu = chuoi.Length % 3;

            if (sodu != 0)
            {
                chuoicd = chuoi.Insert(sodu, ",");
                for (int i = 1; i < chuoi.Length / 3; i++)
                {
                    sodu += 4;
                    chuoicd = chuoicd.Insert(sodu, ",");
                }
            }
            else
            {
                sodu += 3;
                chuoicd = chuoi;
                for (int i = 1; i < chuoi.Length / 3; i++)
                {
                    chuoicd = chuoicd.Insert(sodu, ",");
                    sodu += 4;

                }
            }
            return chuoicd;
        }
        private static string KTText(string text)
        {
            string kqua = "";

            if (text == "000" || text == "00" || text == "0")
            {
                kqua = "";
            }
            else if (text.Length == 3)
            {
                int dv, c, tram;
                dv = int.Parse(text.Substring(text.Length - 1));
                c = int.Parse(text.Substring(1));
                int chuc = c - dv;
                tram = int.Parse(text.Substring(0, 1));

                if (dv == 0 && chuc != 0)
                    kqua = hs[tram.ToString()] + " trăm " + hs[chuc.ToString()].ToString().ToLower() + " ";
                else if (chuc == 0 && dv == 0)
                    kqua = hs[tram.ToString()] + " trăm ";
                else if (tram == 0 && chuc == 0)
                {
                    if (dv != 1)
                        kqua = "không trăm " + hs[chuc.ToString()].ToString().ToLower() + " " + hs[dv.ToString()].ToString().ToLower() + " ";
                    else
                        kqua = "không trăm " + hs[chuc.ToString()].ToString().ToLower() + " một ";
                }
                else if (tram == 0)
                {
                    if (dv != 1)
                        kqua = "không trăm " + hs[chuc.ToString()].ToString().ToLower() + " " + hs[dv.ToString()].ToString().ToLower() + " ";
                    else
                        kqua = "không trăm " + hs[chuc.ToString()].ToString().ToLower() + " mốt ";
                }
                else
                {
                    if (dv != 1)
                        kqua = hs[tram.ToString()] + " trăm " + hs[chuc.ToString()].ToString().ToLower() + " " + hs[dv.ToString()].ToString().ToLower() + " ";
                    else
                        kqua = hs[tram.ToString()] + " trăm " + hs[chuc.ToString()].ToString().ToLower() + " mốt ";
                }
            }
            else if (text.Length == 2)
            {
                int dv;
                dv = int.Parse(text.Substring(1));
                int chuc = int.Parse(text) - dv;
                if (dv == 0)
                    kqua = hs[chuc.ToString()].ToString() + " ";
                else
                {
                    if (dv != 1 || dv != 5)
                        kqua = hs[chuc.ToString()].ToString() + " " + hs[dv.ToString()].ToString().ToLower() + " ";
                    else if (dv == 1)
                        kqua = hs[chuc.ToString()].ToString() + " một ";
                    else if (dv == 5 && chuc == 0)
                        kqua = hs[chuc.ToString()].ToString() + " năm ";
                }
            }
            else if (text.Length == 1)
            {
                int dv;
                dv = int.Parse(text);
                if (dv != 5)
                    kqua = hs[dv.ToString()].ToString() + " ";
                else
                    kqua = "năm ";

            }
            return kqua;
        }

        #endregion




    }
}
